<script setup>
import {getCurrentInstance, reactive, ref, toRefs} from "vue";
import BaseInfoForm from "@/views/lims/contractAnalysis/form/BaseInfoForm.vue";
import SampleInfoForm from "@/views/lims/contractAnalysis/form/SampleInfoForm.vue";
import InspectInfoForm from "@/views/lims/contractAnalysis/form/InspectInfoForm.vue";
import AfterSalesForm from "@/views/lims/contractAnalysis/form/AfterSalesForm.vue";
import PaymentForm from "@/views/lims/contractAnalysis/form/PaymentForm.vue";
import {GUID, toCamKey} from "@/utils/wanfeng";
import {LimsConfig, LimsFormChild, LimsFormConfig} from "@/api/lims/common/LimsModel";
import {genCodeNumber, getTableRecord, saveFormData} from "@/api/lims/sysManager/table";
import {parseParams} from "@/utils/ruoyi";
import {getActionStatusMapByTemplate, saveWorkFlow} from "@/api/lims/sysManager/workFlow";
import {getDecodeData} from "@/api/lims/sop";
import moment from "moment";
const { proxy } = getCurrentInstance()
const data = reactive({
  paymentForm:{}
})

const activeTab = ref('baseInfo')
const baseInfo = ref(null)
const sampleInfo = ref()
const inspectInfo = ref()
const afterSales = ref()
const paymentInfo = ref()
const formTabs = ref([
  {name: 'baseInfo', tab: baseInfo, valid:false},
  {name: 'sampleInfo', tab: sampleInfo, valid:false},
  {name: 'inspectInfo', tab: inspectInfo, valid:false},
  {name: 'afterSales', tab: afterSales, valid:false},
  {name: 'paymentInfo', tab: paymentInfo, valid:false},
])

const form = ref({
  ORDER_ID: '',
  ORDER_NUM: '',
  APPLICANT_NAME:'',
  PAYMENT_DISCOUNT: 100,
  SAMPLE_DATE: moment.now()
})

const operator = ref('')

const loadData = () =>{
  let param = parseParams(window.location.href)
  console.log('param value is ::::', param)
  if (param && Object.keys(param).indexOf('orderId') > -1){
    form.value.ORDER_ID = param.orderId
    let config = new LimsConfig('M_CONTRACT_ANALYSIS')
    config.filters.eq('ORDER_ID', form.value.ORDER_ID)
    operator.value = 'edit'
    getTableRecord(config).then(response => {
      form.value = response.data[0]
    })
  }else {
    operator.value = 'add'
    form.value.ORDER_ID = GUID()
    form.value.ORDER_NUM = genCodeNumber('orderNumber')
  }
  console.log('form value is ::::', form.value)
}


const {paymentForm} = toRefs(data)

const settingPayment = (charges) =>{
  console.log('charges is :::', charges)
  paymentInfo.value.settingPayment(charges)
}
const nextTab = (name) => {
  if (name){
    activeTab.value = name
    return
  }
  switch (activeTab.value){
    case 'baseInfo':
          activeTab.value = 'sampleInfo'
          break
    case 'sampleInfo':
          activeTab.value = 'inspectInfo'
          break
    case 'inspectInfo':
      activeTab.value = 'afterSales'
          break
    case 'afterSales':
      activeTab.value = 'paymentInfo'
          break
  }
}

/**
 * 保存：保存本页（tab)内容并进行校验，
 * 保存成功后跳转下一页
 */
const save = () => {
  formTabs.value.forEach(item => {
    //该写法需要每个tab暴露form表单且form表单名称为:formInfo
    if (item.name === activeTab.value){
      item.tab.formInfo.validate(valid => {
        if (valid ){
          form.value.COMMIT_STATUS = '保存'
          submitForm(false, true)
        }
      })
    }
  })
}

/**
 * 提交表单到工作流
 * 校验所有form表单的必填信息
 * 若有未填写的跳转到对应的tab页面
 */
const commit = (i) => {
  i =  i ? i:0
  console.log('i:::',i)
  formTabs.value[i].tab.formInfo.validate(valid =>{
    if (!valid) {
      nextTab(formTabs.value[i].name)
      return valid
    }else {
      if (i < formTabs.value.length-1){
        i++
        commit(i)
      }else {
        console.log('所有form表单校验通过')
        commitForm()
        return valid
      }
    }
  })
}

//提交需要连通子表一块儿提交
const submitForm = (isCommitWorkflow, next) => {
    let model = Object.assign({}, form.value)
    let formConfig = new LimsFormConfig('M_CONTRACT_ANALYSIS', model, operator.value)
    // if (model.subSubjects) delete model.subSubjects
    console.log('model is :::', model)
    if (inspectInfo.value.inspectProjectList && inspectInfo.value.inspectProjectList.length > 0){
      let childRow = []
      inspectInfo.value.inspectProjectList.forEach(item => {
        let child = Object.assign({}, item)
        childRow.push(child)
      })
      console.log('childRow is :::', childRow, inspectInfo.value.inspectProjectList)
      formConfig.addChild('M_CONTRACT_ANALYSIS_SUBJECT', childRow)
    }
    saveFormData(formConfig).then(response => {
      if (response.success){
        operator.value = 'edit'
        proxy.$modal.msgSuccess('保存成功')
        if (next){
          nextTab()
        }else {
          closeCurrentPage()
        }
      }else {
        proxy.$modal.msgError('保存失败：'+response.message)
      }
      console.log('response', response)
    })
}

const commitForm = () =>{
  if (!form.value.REPORT_NUMBER_PREPEND){
    proxy.$modal.alertWarning('报告编号前缀必填，请选择报告编号前缀后再进行提交')
    return
  }
  form.value.COMMIT_STATUS = '已提交'
  //生成报告编号
  let sql = 'select dbo.FN_GEN_REPORT_NO(\'' +form.value.REPORT_NUMBER_PREPEND+'\', 5, 1) AS REPORT_NO'
  getDecodeData('sqlserver', sql).then(response => {
    console.log('genReportCode response is ::', response)
    if (response.success && response.data  && response.data.length > 0){
      form.value.REPORT_NO = response.data[0].REPORT_NO
      submitForm(false, false)
    }
  })
}


const closeCurrentPage = () =>{
 window.parent.closeCallBack()
}

const numberPrepend = ref([
    { label:'HYC', value:'HYC'},
    { label:'HHC', value:'HHC'},
    { label:'HDC', value:'HDC'},
    { label:'GYC', value:'GYC'},
    { label:'GHC', value:'GHC'},
    { label:'RHC', value:'RHC'},
    { label:'YYC', value:'YYC'},
    { label:'YHC', value:'YHC'},
    { label:'SDC', value:'SDC'},
    { label:'ZHC', value:'ZHC'},
    { label:'HYE', value:'HYE'},
    { label:'HHE', value:'HHE'},
    { label:'HDE', value:'HDE'},
])


loadData()
</script>

<template>
  <el-form :inline="true">
    <el-form-item label="报告编号">
      <el-input v-model="form.REPORT_NO">
        <template #prepend>
          <el-select v-model="form.REPORT_NUMBER_PREPEND" style="width: 100px">
            <el-option v-for="item in numberPrepend" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </template>
<!--        <template #append>-->
<!--          <el-button @click="commitForm">生成</el-button>-->
<!--        </template>-->
      </el-input>
    </el-form-item>
    <el-form-item label="单号">
      <el-input disabled></el-input>
    </el-form-item>
  </el-form>
  <el-tabs v-model="activeTab" type="border-card">
    <el-tab-pane label="基本信息" name="baseInfo">
    <base-info-form ref="baseInfo" :form="form" @next="nextTab"></base-info-form>
    </el-tab-pane>
    <el-tab-pane label="样品信息" name="sampleInfo">
      <sample-info-form :form="form" ref="sampleInfo"></sample-info-form>
    </el-tab-pane>
    <el-tab-pane label="检验信息" name="inspectInfo">
      <inspect-info-form ref="inspectInfo" :form="form" @setting-payment="settingPayment"></inspect-info-form>
    </el-tab-pane>
    <el-tab-pane label="售后信息" name="afterSales">
      <after-sales-form :form="form"  ref="afterSales"></after-sales-form>
    </el-tab-pane>
    <el-tab-pane label="缴费信息" name="paymentInfo">
      <payment-form ref="paymentInfo" :form="form"></payment-form>
    </el-tab-pane>
  </el-tabs>
  <el-affix position="bottom" :offset="20" style="float: right">
<!--    <el-button type="success" @click="loadData">加载</el-button>-->
    <el-button type="success" :disabled="form.COMMIT_STATUS === '已提交'" @click="save">保存</el-button>
    <el-button type="primary" :disabled="form.COMMIT_STATUS === '已提交'" v-if="activeTab === 'paymentInfo'" @click="commit(0)" >提交</el-button>
    <el-button type="danger" @click="closeCurrentPage">关闭</el-button>
  </el-affix>
</template>

<style scoped lang="scss">


</style>